#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>

typedef websocketpp::server<websocketpp::config::asio> wsserver_t;

static const uint16_t defaultport = 8080;

void on_open(websocketpp::connection_hdl hdl)
{
    std::cout << "websocket 握手连接成功" << std::endl;
}

void on_close(websocketpp::connection_hdl hdl)
{
    std::cout << "websocket 连接关闭" << std::endl;
}

void on_message(wsserver_t *server, websocketpp::connection_hdl hdl, wsserver_t::message_ptr msg)
{
    std::string body = msg->get_payload();
    std::cout << "收到消息: " << body << std::endl;

    wsserver_t::connection_ptr conn = server->get_con_from_hdl(hdl);
    conn->send("server reponse: " + body, websocketpp::frame::opcode::value::text);
}

int main()
{
    wsserver_t server;
    // 关闭日志
    server.set_access_channels(websocketpp::log::alevel::none);
    // 初始化asio异步框架
    server.init_asio();

    server.set_open_handler(on_open);
    server.set_close_handler(on_close);
    server.set_message_handler(std::bind(on_message, &server, std::placeholders::_1, std::placeholders::_2));

    server.set_reuse_addr(true);
    server.listen(defaultport);
    server.start_accept();
    server.run();
    return 0;
}